package com.javasm.duanju.controller;


import com.javasm.duanju.dto.VideoTagDTO;
import com.javasm.duanju.entity.VideoTags;
import com.javasm.duanju.service.VideoTagsService;
import commom.domain.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * (VideoTags)表控制层
 *
 * @author makejava
 * @since 2025-02-26 10:56:54
 */
@RestController
@RequestMapping("/videoTags")
public class VideoTagsController{
    @Autowired
    VideoTagsService videoTagsService;
//    修改
@PostMapping("/updateTags")
    public AjaxResult updateTags(@RequestBody VideoTagDTO videoTagDto){

    String tags = videoTagDto.getTags();
    if (videoTagDto.getId()==null){
        throw new RuntimeException("id不能为空");
    }
    VideoTags videoTags = videoTagsService.getById(videoTagDto.getId());
    String[] arr = tags.split(",");
    StringBuilder sb = new StringBuilder(videoTags.getTags());
//    判断标签是否存在
    for (String tag : arr) {
        if (!videoTags.getTags().contains(tag)){
           sb.append(",").append(tag);
        }
    }
    videoTags.setTags(sb.toString());
    videoTagsService.updateById(videoTags);
    return AjaxResult.ok("标签修改成功");
}
    @GetMapping("/tagAll")
    //标签查询，根据id查询
    public AjaxResult tagsAll( @RequestParam(value = "tid",defaultValue = "1") Integer tid) {
        // 从数据库获取所有标签数据
        VideoTags videoTags = videoTagsService.getById(tid);
        String[] arr = videoTags.getTags().split(",");

        // 创建一个列表来保存每个标签对应的VideoTagDto对象
        List<VideoTagDTO> tagsList = new ArrayList<>();
        for (String tag : arr) {
            VideoTagDTO videoTagDto = new VideoTagDTO();
            videoTagDto.setValue(tag.trim());
            videoTagDto.setLabel(tag.trim());
            tagsList.add(videoTagDto);
        }
        // 返回AjaxResult对象，包含处理好的标签列表
        return AjaxResult.ok(tagsList);
    }
//    添加功能
    @PostMapping("/addAll")
    public AjaxResult addAll(@RequestBody VideoTagDTO videoTagDto) {
        String tags = videoTagDto.getTags();
        VideoTags videoTags = new VideoTags();
        videoTags.setTags(tags);
        videoTagsService.save(videoTags);
        return AjaxResult.ok("标签添加成功");
    }
//    删除标签
@GetMapping("/delTags")
public AjaxResult delTags(@RequestBody VideoTagDTO videoTagDto){
    VideoTags videoTags = videoTagsService.getById(videoTagDto.getId());
    String tags = videoTags.getTags();
    String[] oldArr = videoTags.getTags().split(",");
    String newTags = Arrays.stream(oldArr)
            .filter(item -> !tags.contains(item))
            .collect(Collectors.joining(","));
    videoTags.setTags(newTags);
    videoTagsService.updateById(videoTags);
    return AjaxResult.ok("删除标签成功");
}

}

